package com.lgl.tools;

import com.lgl.serializer.ISerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Auther: Brook
 * @Date: 2020/10/18 16:44
 * @Description:
 */
public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;
    private ISerializer serializer;

    public RpcEncoder(Class<?> clazz, ISerializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
        if (clazz != null && clazz.isInstance(msg)) {
            byte[] bytes = serializer.serialize(msg);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
